//
//  PictureFieldController.m
//  MClient
//
//  Created by  史正烨 on 09-11-2.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import <MediaPlayer/MediaPlayer.h>
#import "FileListViewController.h"
#import "MServerDAO.h"
#import "fileViewController.h"
#import "MCFunction.h"
#import "MCUIToolkit.h"
#import "DocFileListDisplayController.h"
#import "CASignUntitledViewController.h"
#import "CustomMoviePlayer.h"

@implementation FileListViewController
@synthesize fieldData;
@synthesize valueField;
@synthesize field;
@synthesize isViewMode;
@synthesize cacheFile;
@synthesize fileData;
@synthesize operateFlag;

- (id)init {
	if (self = [super init]) {
		self.hidesBottomBarWhenPushed = YES;
	}
	return self;
}

- (void)leftBarButton:(NSString*)aTitle withStyle:(UIBarButtonItemStyle)style selector:(SEL)sel
{
	UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:aTitle 
															   style:style 
															  target:self		
															  action:sel];
	self.navigationItem.leftBarButtonItem = button;
	[button release]; button = nil;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	_oldToolBarHidden = [self.navigationController isToolbarHidden];
	
	fileArray = [self.fieldData objectForKey:@"fi"];
	if (fileArray == nil) {
		fileArray = [NSMutableArray array];
		[self.fieldData setObject:fileArray forKey:@"fi"];
	} else {
		for (NSMutableDictionary *fileInfo in fileArray) {
			if (![fileInfo objectForKey:@"state"]) {
				[fileInfo setObject:@"normal" forKey:@"state"];
			}
		}
	}
	fileArrayTemp = [[MCUIToolkit getObjectCopy:fileArray] retain];

	for (int i = 0; i < [fileArrayTemp count]; i++) {
		NSMutableDictionary *fileTemp = [fileArrayTemp objectAtIndex:i];
		if ([[fileTemp objectForKey:@"state"] isEqualToString:@"del"] || [[fileTemp objectForKey:@"state"] isEqualToString:@"addDel"]) {
			[fileArrayTemp removeObjectAtIndex:i];
			i--;
		}
	}
	
	if (self.isViewMode) {
		self.title = @"文件查阅";
		[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
	}
	else {
		self.title = @"文件处理";
		[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectAction:)];
		
		bool video = NO;
		bool camera = NO;
		bool photo = NO;
		if ([field objectForKey:@"fun"]) {
			NSString *value = [field objectForKey:@"fun"];
			NSArray *functions = [value componentsSeparatedByString:@";"];
			for (NSString *fun in functions) {
				if ([@"1" isEqualToString:fun]) {
					video = YES;
					continue;
				}
				if ([@"2" isEqualToString:fun]) {
					camera = YES;
					continue;
				}
				if ([@"3" isEqualToString:fun]) {
					photo = YES;
					continue;
				}
			}
		}else {
			video = YES;
			camera = YES;
			photo = YES;
		}
		UITabBar *tabBar = [[UITabBar alloc] initWithFrame:CGRectMake(0.0, self.height-nTabBarHeight, self.width, nTabBarHeight)];
		tabBar.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
		tabBar.delegate = self;
		NSMutableArray * tabBarItems = [[NSMutableArray alloc] init];
		UITabBarItem *tabBarItem;
		if (camera) {
			tabBarItem = [[UITabBarItem alloc] initWithTitle:@"拍摄照片" image:[UIImage imageNamed:@"camera.png"] tag:1];
			if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
				tabBarItem.enabled = YES;
			else {
				tabBarItem.enabled = NO;
			}
			[tabBarItems addObject:tabBarItem];
			[tabBarItem release];
		}
		if (video) {
			tabBarItem = [[UITabBarItem alloc] initWithTitle:@"录制视频" image:[UIImage imageNamed:@"camera.png"] tag:2];
			if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
				tabBarItem.enabled = YES;
			else {
				tabBarItem.enabled = NO;
			}
			[tabBarItems addObject:tabBarItem];
			[tabBarItem release];
		}
		if (photo) {
			tabBarItem = [[UITabBarItem alloc] initWithTitle:@"从照片库中选择" image:[UIImage imageNamed:@"photos.png"] tag:3];
			[tabBarItems addObject:tabBarItem];
			[tabBarItem release];
		}
		[self addOtherTabBarItem:tabBarItems];

		[tabBar setItems:tabBarItems];
		[tabBarItems release];
		[self.clientView addSubview:tabBar];
		self.tableview.frame = CGRectMake(0, 0, self.width, self.height-tabBar.frame.size.height);
		[tabBar release];
	}	
	
	self.addHelpButton = YES;
	self.helpUrl = @"/iphone/help/chapter05-03-03.html";
}

- (void)viewWillDisappear:(BOOL)animated {
	[self.navigationController setToolbarHidden:_oldToolBarHidden animated:YES];
}

- (void)addOtherTabBarItem: (NSMutableArray *)tabBarItems {
	/*
	 tabBarItem = [[UITabBarItem alloc] initWithTitle:@"从文件库中选择" image:[UIImage imageNamed:@"master.png"] tag:4];
	 [tabBarItems addObject:tabBarItem];
	 [tabBarItem release];
	 
	 tabBarItem = [[UITabBarItem alloc] initWithTitle:@"手写签名" image:[UIImage imageNamed:@"master.png"] tag:5];
	 [tabBarItems addObject:tabBarItem];
	 [tabBarItem release];
	 */
}

- (void)dealloc {
	[fieldData release];
	[valueField release];
	[field release];
	[cacheFile release];
	[tempLocation release];
	[fileArrayTemp release];
	[fileData release];
	[operateFlag release];
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [fileArrayTemp count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"imageCellIdentifier"];
	if (cell == nil) {
		CGRect cellFrame = CGRectZero;
		cell = [[[UITableViewCell alloc] initWithFrame:cellFrame reuseIdentifier:@"imageCellIdentifier"] autorelease];
		
		UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(270, 12, 16, 16)];
		imageView.tag = 4;
		[cell.contentView addSubview:imageView];
		[imageView release];
		
		UILabel *labelField = [[UILabel alloc] initWithFrame:CGRectMake(40, 3.0, 200, 30)];
		labelField.textAlignment = UITextAlignmentLeft;
		labelField.textColor = [UIColor colorWithRed:0.239 green:0.322 blue:0.255 alpha:1];
		labelField.backgroundColor = [UIColor clearColor];
		labelField.font = [UIFont systemFontOfSize:18];
		labelField.numberOfLines = 1;
		
		labelField.tag = 1;
		[cell.contentView addSubview:labelField];
		[labelField release];
		
		cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
	}
	int row = [indexPath row];
	
	NSMutableDictionary *fileAttribute = [fileArrayTemp objectAtIndex:row];
	NSString *fileExtension = [[[fileAttribute objectForKey:@"fname"] pathExtension] lowercaseString];
	NSArray *knowExtensions = [NSArray arrayWithObjects:@"doc",@"jpeg",@"jpg",@"pdf",@"png",@"ppt",@"rtf",@"tiff",@"txt",@"xls",@"zip",@"docx",@"pptx",@"xlsx",nil];
	
	if ([knowExtensions containsObject:fileExtension]) {
		cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"file-%@.png",fileExtension]];
	}
	else {
		cell.imageView.image = [UIImage imageNamed:@"file-unknow.png"];
	}
	
	
	UILabel *labelField = (UILabel *)[cell.contentView viewWithTag:1];
	labelField.text = [fileAttribute objectForKey:@"fname"];
	if (!self.isViewMode) {
		UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:4];
		NSString *uploadState = [[fileArrayTemp objectAtIndex:row] objectForKey:@"state"];
		if ([uploadState isEqualToString:@"add"]) {
			imageView.image = [UIImage imageNamed:@"folder--plus.png"];
		}
		else {
			imageView.image = [UIImage imageNamed:@"folder.png"];
		}
	}
	return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (self.isViewMode) {
		[self viewFileContent:[indexPath row]];
	}
	else {
		UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择明细操作"
																 delegate:self 
														cancelButtonTitle:@"取消"
												   destructiveButtonTitle:nil 
														otherButtonTitles:@"查阅",/*@"下载",*/@"删除",nil];
		actionSheetFlag = [indexPath row];
		[actionSheet showInView:self.clientView.window];
		[actionSheet release];
	}
}

#pragma mark ---- UITabBar事件处理方法 ----
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
	if(item.tag == 1) {
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		picker.mediaTypes =  [NSArray arrayWithObject:@"public.image"];
		[self presentModalViewController:picker animated:YES];
		[picker release];
	}
	else if(item.tag == 2) {
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
		NSArray *temp_MediaTypes = [UIImagePickerController availableMediaTypesForSourceType:picker.sourceType];
		if (![temp_MediaTypes containsObject:@"public.movie"]) {
			[self messageBox:@"提示" 
					 message:@"您的手机硬件不支持视频录制功能!" 
					delegate:self
		   cancelButtonTitle:nil
		   otherButtonTitles:@"确定"];
			return;
		}
		picker.mediaTypes =  [NSArray arrayWithObject:@"public.movie"];
		[self presentModalViewController:picker animated:YES];
		[picker release];
	}
	else if (item.tag == 3) {
		UIImagePickerController *picker = [[UIImagePickerController alloc] init];
		picker.delegate = self;
		picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        picker.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];//huotianjun 增加，可选择拍摄好的视频文件
		[self presentModalViewController:picker animated:YES];
		[picker release];
	}
	else if (item.tag == 4){
		DocFileListDisplayController *docFileListDisplayController = [[DocFileListDisplayController alloc] init];
		docFileListDisplayController.isMultiFile = YES;
		[self.navigationController pushViewController:docFileListDisplayController animated:YES];
		[docFileListDisplayController release];
	}
	else if (item.tag == 5){
		CASignUntitledViewController* controller = [[CASignUntitledViewController alloc] init];
		controller.isMultiFile = YES;
		[self.navigationController pushViewController:controller animated:YES];
		[controller release];
	}
}

#pragma mark ---- 图片事件处理方法 ----
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	@try {
        [picker dismissModalViewControllerAnimated:YES];
		NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
		if ([mediaType isEqualToString:@"public.image"]){
			self.cacheFile = [MCFunction getTempFileName:@"jpeg"];
			NSString *imageFile = [NSString stringWithFormat:@"%@%@",NSTemporaryDirectory(),self.cacheFile];
			
			UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
			[UIImageJPEGRepresentation(image, 0.0f) writeToFile:imageFile atomically:YES];//huotianjun增加压缩度
        }
		else if([mediaType isEqualToString:@"public.movie"]){
			self.cacheFile = [MCFunction getTempFileName:@"mov"];
			NSString *videoFile = [NSString stringWithFormat:@"%@%@",NSTemporaryDirectory(),self.cacheFile];
			
			NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
			NSData *videoData = [NSData dataWithContentsOfURL:videoURL];
			[videoData writeToFile:videoFile atomically:YES];
		}
		
		[self getUploadFileName];
		self.fileData = [NSInputStream inputStreamWithFileAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), cacheFile]];
        
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];
	}
    
}

- (void) getUploadFileName{
	self.operateFlag = @"getUploadFileName";
	[[MServerDAO sharedInstance] getUploadFileNameAsync:self];	
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	[picker dismissModalViewControllerAnimated:YES];
}

- (void) getDataFromServerSuccess: (NSMutableDictionary *)returnValue {
	if ([self.operateFlag isEqualToString:@"getUploadFileName"]) {
		tempLocation = [returnValue retain];
		self.operateFlag = @"uploadFile";
		[[MServerDAO sharedInstance] uploadFileAsync:@"upload" 
											location:tempLocation 
												data:fileData
											delegate:self];	
	} else if ([self.operateFlag isEqualToString:@"uploadFile"]) {
		NSMutableDictionary *newFile = [NSMutableDictionary dictionary];
		[newFile setObject:cacheFile forKey:@"fname"];
		[newFile setObject:tempLocation forKey:@"lcn"];
		[newFile setObject:@"add" forKey:@"state"];
		[fileArray addObject:newFile];
		
		NSMutableDictionary *newFileCopy = [MCUIToolkit getObjectCopy:newFile];
		[fileArrayTemp addObject:newFileCopy];
		[self messageBox:@"操作成功"
				 message:@"上传成功!"
				delegate:nil
	   cancelButtonTitle:nil
	   otherButtonTitles:@"确定"];
		
		[self.tableview reloadData];
	} else if ([self.operateFlag isEqualToString:@"downloadFile"]) {
		[self messageBox:@"操作成功"
				 message:@"下载成功!"
				delegate:nil
	   cancelButtonTitle:nil
	   otherButtonTitles:@"确定"];
	}
}

- (void)getServerError: (NSString *)returnCode returnMessage:(NSString *)returnMessage {
	[super getServerError:returnCode returnMessage:returnMessage];
}

#pragma mark ---- 事件处理方法 ----
- (void) selectAction: (id) sender {
	NSString *fileNames = @"";

	for(NSDictionary *fileInfo in fileArrayTemp) {
		fileNames = [fileNames stringByAppendingFormat:@"%@,", [fileInfo objectForKey:@"fname"]];
	}
	if ([fileNames length] > 0) {
		fileNames = [fileNames substringToIndex:[fileNames length] - 1];
	}
	self.valueField.text = fileNames;
	
	[self.navigationController popViewControllerAnimated:YES];
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	int row = actionSheetFlag;
	if (buttonIndex == 0) {
		[self viewFileContent:row];	
	}
	/*
	 else if (buttonIndex == 1) {
	 [self downloadFromServer:row];
	 }*/
	else if (buttonIndex == 1) {
		UIAlertView *alert = [[UIAlertView alloc] 
							  initWithTitle:@"确定删除?" 
							  message:nil
							  delegate:self 
							  cancelButtonTitle:@"取消" 
							  otherButtonTitles:@"确定",nil];
		[alert show];
		[alert release];
	}
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (actionSheetFlag == -1) {
		if (buttonIndex == 1) {
			[self.navigationController popViewControllerAnimated:YES];
		}
	}
	else {
		if (buttonIndex == 1) {
			[self deleteFile:actionSheetFlag];
		}
	}
}

- (void)downloadFromServer: (int) row {
	if ([[[fileArrayTemp objectAtIndex:row] objectForKey:@"state"] isEqualToString:@"add"]) {
		[self messageBox:@"操作提示"
				 message:@"文件已在本地文件库中，无需下载！"
				delegate:nil
	   cancelButtonTitle:nil
	   otherButtonTitles:@"确定"];
		return;
	}
	
	
	NSString *dataFrom = [self.fieldData objectForKey:@"df"] == nil?@"":[self.fieldData objectForKey:@"df"];
	NSMutableDictionary *fileInfo = [fileArrayTemp objectAtIndex:row];
	NSString *fileName = [fileInfo objectForKey:@"fname"];
	if (fileName == nil || [fileName length] == 0)
		return;
	NSString *fileLocation = [fileInfo objectForKey:@"lcn"];	
	NSString *type = @"";
	
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *cacheFileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:fileName];
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	[fileManager changeCurrentDirectoryPath:[[paths objectAtIndex:0] stringByExpandingTildeInPath]];
	[fileManager createFileAtPath:fileName contents:nil attributes:nil];
	self.operateFlag = @"downloadFile";
	
	[[MServerDAO sharedInstance] downloadFileAsync:@"download"
										  dataFrom:dataFrom
										  location:fileLocation
										  fileName:fileName
											  page:0
											  type:type 
									  saveLocation:cacheFileName 
										  delegate:self];
}


- (void)deleteFile:(int)row {
	NSString *fileName = [[fileArrayTemp objectAtIndex:row] objectForKey:@"fname"];
	NSString *fileLocation = [[fileArrayTemp objectAtIndex:row] objectForKey:@"lcn"];
	
	for (NSMutableDictionary *fileInfo in fileArray) {
		if ([[fileInfo objectForKey:@"fname"] isEqualToString:fileName] && [[fileInfo objectForKey:@"lcn"] isEqualToString:fileLocation]) {
			if ([[fileInfo objectForKey:@"state"] isEqualToString:@"normal"]) {
				[fileInfo setObject:@"del" forKey:@"state"];
			} else if ([[fileInfo objectForKey:@"state"] isEqualToString:@"add"]){
				[fileInfo setObject:@"addDel" forKey:@"state"];
			}
		}
	}
	[fileArrayTemp removeObjectAtIndex:row];
	[self.tableview reloadData];
}


- (void) viewFileContent: (int) row  {
	if ([[[fileArrayTemp objectAtIndex:row] objectForKey:@"state"] isEqualToString:@"add"]) {
		NSString *name = [[fileArrayTemp objectAtIndex:row] objectForKey:@"fname"];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *cacheFileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];

		if ([name hasSuffix:@"mov"]) {
            // Create custom movie player   
            CustomMoviePlayerViewController *moviePlayer = [[[CustomMoviePlayerViewController alloc] initWithPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), name]] autorelease];//huotianjun 从临时文件目录中调出视频显示。
            
            // Show the movie player as modal
            [self presentModalViewController:moviePlayer animated:YES];//huotianjun
            
            // Prep and play the movie
            [moviePlayer readyPlayer];    //huotianjun
			//[self messageBox:@"提示" message:@"视频文件暂不支持播放功能!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定"];
			return;
		}
		FileViewController*fileView = [[FileViewController alloc] init];
		[self.navigationController pushViewController:fileView animated:YES];
		[fileView release];
		
		//NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		//NSString *cacheFileName = [[paths objectAtIndex:0] stringByAppendingPathComponent:name];
		
		NSFileManager* manager = [NSFileManager defaultManager];
		if (![manager fileExistsAtPath:cacheFileName]) {
			cacheFileName = [NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), name];
			if (![manager fileExistsAtPath:cacheFileName]) {
				return;
			}
		}
		
		/*NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:cacheFileName];
		NSURLRequest *req = [NSURLRequest requestWithURL:fileUrl];
		[fileUrl release];
		[fileView.webView loadRequest:req];
		fileView.webView.scalesPageToFit =  YES;
		fileView.title = name;*/
		NSURL *fileUrl = [[NSURL alloc] initFileURLWithPath:cacheFileName];
		NSURLRequest *req = [NSURLRequest requestWithURL:fileUrl];
		[fileUrl release];
		//解决图片下载后默认显示远小于原图的问题。
		NSString* szExtension = [[cacheFileName pathExtension] lowercaseString];
		if ([szExtension isEqualToString:@"png"] || [szExtension isEqualToString:@"bmp"] ||
			[szExtension isEqualToString:@"jpg"] || [szExtension isEqualToString:@"jpeg"] ||
			[szExtension isEqualToString:@"gif"] || [szExtension isEqualToString:@"psd"] ||
			[szExtension isEqualToString:@"swf"]) {
			UIImage *image = [UIImage imageWithContentsOfFile:cacheFileName];
			CGSize size = [image size];
			NSString *imageHTML = nil;
			if (size.width <= self.width && size.height <= self.height) {
				NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
				@"<html xmlns='http://www.w3.org/1999/xhtml'>"
				@"<head>"
				@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
				@"</head>"
				@"<body><img src='%@' width='%f' height='%f'></body>"
				@"</html>";
				imageHTML  = [NSString stringWithFormat:htmlString, fileUrl, size.width, size.height];
			} else if (size.width <= self.width || size.height <= self.height) {
				NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
				@"<html xmlns='http://www.w3.org/1999/xhtml'>"
				@"<head>"
				@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
				@"<style type='text/css'>.customImg{%@='%f'}</style>"
				@"</head>"
				@"<body><img src='%@' class='customImg'></body>"
				@"</html>";
				imageHTML  = [NSString stringWithFormat:htmlString, ((size.width <= self.width) ? @"width" : @"height"),
							  ((size.width <= self.width) ? size.width : size.height), fileUrl];
			} else if (size.width <= size.height) {
				NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
				@"<html xmlns='http://www.w3.org/1999/xhtml'>"
				@"<head>"
				@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
				@"<style type='text/css'>.customImg{width='%f'}</style>"
				@"</head>"
				@"<body><img src='%@' class='customImg'></body>"
				@"</html>";
				imageHTML  = [NSString stringWithFormat:htmlString, self.width, fileUrl];
			} else {
				NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
				@"<html xmlns='http://www.w3.org/1999/xhtml'>"
				@"<head>"
				@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
				@"<style type='text/css'>.customImg{height='%f'}</style>"
				@"</head>"
				@"<body><img src='%@' class='customImg'></body>"
				@"</html>";
				imageHTML  = [NSString stringWithFormat:htmlString, self.height, fileUrl];
			}
			if (imageHTML) {
				MCLog(@"imageHTML=%@", imageHTML);
				fileView.webView.scalesPageToFit = YES;
				[fileView.webView loadHTMLString:imageHTML baseURL:nil];
			}
		} else if ([szExtension isEqualToString:@"html"] || [szExtension isEqualToString:@"htm"]) {
			NSData *htmlData = [NSData dataWithContentsOfFile:cacheFileName];  
			[fileView.webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"GBK" baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]]; 
			fileView.webView.scalesPageToFit = YES;
			fileView.title = name;
		}
		else {
			fileView.webView.scalesPageToFit = YES;
			fileView.title = name;
			[fileView.webView loadRequest:req];
		}
		return;
	}
	NSString *dataFrom = [self.fieldData objectForKey:@"df"] == nil?@"":[self.fieldData objectForKey:@"df"];
	NSMutableDictionary *fileInfo = [fileArrayTemp objectAtIndex:row];
	
	[MCFunction filePreview:self
				   dataFrom:dataFrom
				   fileInfo:fileInfo];
	/*
	NSString *fileName = [fileInfo objectForKey:@"fname"];
	if (fileName == nil || [fileName length] == 0)
		return;
	if ([fileName hasSuffix:@"avi"]) {
		[self messageBox:@"提示" 
				 message:@"视频文件暂不支持播放功能!" 
				delegate:self
	   cancelButtonTitle:nil
	   otherButtonTitles:@"确定"];
		return;
	}
	NSString *fileLocation = [fileInfo objectForKey:@"lcn"];
	
	NSMutableDictionary *fileAttribute = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
										  fileName,@"fileName",
										  fileLocation,@"fileLocation",
										  @"download",@"actionType",
										  dataFrom,@"dataFrom",nil];
	FileViewController *fileView = [[FileViewController alloc] init];
	fileView.title = @"文件下载中...";
	fileView.fileAttribute = fileAttribute;
	[self.navigationController pushViewController:fileView animated:YES];
	
	[fileView getDataFromServer];
	[fileView release];
	 */
}

@end
